package com.atguigu.tingshu.user.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.atguigu.tingshu.common.login.GuiguLogin;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.hibernate.validator.internal.constraintvalidators.hv.UUIDValidator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Tag(name = "微信授权登录接口")
@RestController
@RequestMapping("/api/user/wxLogin")
@Slf4j
public class WxLoginApiController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitService rabbitService;


    @GuiguLogin
    @Operation(summary = "更新用户信息")
    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody UserInfoVo userInfoVo){
        Long userId = AuthContextHolder.getUserId();
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setNickname(userInfoVo.getNickname());
        userInfo.setAvatarUrl(userInfoVo.getAvatarUrl());

        userInfoService.updateById(userInfo);
        return Result.ok();
    }




//获取用户信息
    @GuiguLogin
    @Operation(summary = "获取登录信息")
    @GetMapping("/getUserInfo")
    public Result getUserInfo(){
        Long userId = AuthContextHolder.getUserId();

        return Result.ok(userInfoService.getUserInfoVoByUserId(userId));
    }




    //code前端传递过来
    @GetMapping("/wxLogin/{code}")
        public Result wxLogin(@PathVariable("code") String code) throws WxErrorException {

            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            String openId = sessionInfo.getOpenid();


            LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserInfo::getWxOpenId,openId);
            UserInfo userInfo = userInfoService.getOne(wrapper);

            if(userInfo == null) {
                userInfo = new UserInfo();
                userInfo.setNickname("听友"+System.currentTimeMillis());
                userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
                userInfo.setWxOpenId(openId);
                userInfoService.save(userInfo);

                rabbitService.sendMessage(MqConst.EXCHANGE_USER, MqConst.ROUTING_USER_REGISTER, userInfo.getId());

            }
        String token = UUID.randomUUID().toString().replaceAll("-", "");
            redisTemplate.opsForValue().set(token, userInfo,300, TimeUnit.MINUTES);

        Map<String, Object> map = new HashMap<>();
        map.put("token",token);

        return Result.ok(map);

    }













}
